import {login} from '../../services/common/common';
import {message} from 'antd';
import {browserHistory} from 'dva/router';
import Constants from '../../utils/Constants';

export default {
    namespace: 'login',
    state: {
        isNeedVerifyCode: false // 是否需要图形验证码
    },

    reducers: {
        //刷新state
        refreshState(state, { payload }) {
            return { ...state, ...payload }
        },
    },
    effects: {
        *login({ payload }, { call, put, select }) {
            const res = yield call(login, { loginId: payload.loginId, password: payload.password, verifyCode: payload.verifyCode, token: payload.token });
            if (res && res.data.resultCode === "ok") {
                if (!res.data.content.sessionId && res.data.content.needVerifyCode) {//首次输入用户名密码错误
                    yield put({
                        type: 'refreshState',
                        payload: { isNeedVerifyCode: true }
                    });
                    message.error("用户名或者密码错误");
                } else {
                    if (res.data.content.sessionId) {
                        let urls = [];
                        (res.data.content.menus ? res.data.content.menus : []).map(item => urls.push(item.url));
                        sessionStorage.setItem(Constants.USER_MENU, JSON.stringify(urls));
                        sessionStorage.setItem(Constants.ACJSESSIONID, res.data.content.sessionId);
                        sessionStorage.setItem(Constants.USER_NAME, res.data.content.userName);
                        sessionStorage.setItem(Constants.USER_RIGHTS, res.data.content.rightValues);
                        browserHistory.push(res.data.content.defaultMenu)
                    }
                }
            }
        }
    }
};
